/**************************************************************************************** 
 Copyright © 2003-2012 hbasesoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.hbasesoft.hamibot.service;

import java.io.File;
import java.io.IOException;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.stereotype.Component;

import com.hbasesoft.framework.cache.core.CacheHelper;
import com.hbasesoft.framework.common.GlobalConstants;
import com.hbasesoft.framework.common.InitializationException;
import com.hbasesoft.framework.common.utils.io.IOUtil;
import com.hbasesoft.framework.common.utils.logger.LoggerUtil;

/**
 * <Description> <br>
 * 
 * @author 王伟<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2024年12月24日 <br>
 * @since V1.0<br>
 * @see com.hbasesoft.hamibot.service <br>
 */
@Component
public class IpService4Local {

    /** */
    private static final String FILE_NAME = "ip2region.xdb";

    /** */
    private static final String FILE_STORAGE_PATH = GlobalConstants.FILE_STORAGE_PATH + "/ip";

    /** 查询工具 */
    private Searcher searcher;

    /**
     * IP 地址初始化
     */
    public IpService4Local() {
        init();
    }

    /**
     * Description: <br>
     * 
     * @author 王伟<br>
     * @taskId <br>
     * @param ip
     * @return <br>
     */
    public String getIpInfo(final String ip) {
        return CacheHelper.getCacheData("ip" + ip, () -> {
            try {
                return searcher.search(ip);
            }
            catch (Exception e) {
                LoggerUtil.error(e);
            }
            return "未知";
        });
    }

    private void init() {
        LoggerUtil.info("开始初始化ip数据库");
        File dir = new File(FILE_STORAGE_PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File dbFile = new File(dir, FILE_NAME);
        if (!dbFile.exists()) {
            LoggerUtil.info("复制数据文件" + dbFile.getAbsolutePath());
            IOUtil.copyFileFromInputStream(dbFile.getAbsolutePath(),
                this.getClass().getClassLoader().getResourceAsStream(FILE_NAME));
            LoggerUtil.info("复制成功！");
        }

        try {
            LoggerUtil.info("建立IP数据库索引");
            byte[] vIndex = Searcher.loadVectorIndexFromFile(dbFile.getAbsolutePath());
            searcher = Searcher.newWithVectorIndex(dbFile.getAbsolutePath(), vIndex);
        }
        catch (IOException e) {
            LoggerUtil.error(e);
            throw new InitializationException(e);
        }

    }
}
